package com.jiangyg.mall.elasticsearch;

import com.jiangyg.mall.core.support.env.EnvConstant;
import com.jiangyg.mall.core.exception.CoreException;
import com.jiangyg.mall.core.utils.Logger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Objects;

/**
 * 类描述：Elasticsearch 配置
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-11-29
 */
@Slf4j
@Configuration
public class ElasticsearchAutoConfiguration {

    @Bean
    public RestHighLevelClient esRestClient() {
        Logger.info(log, () -> "[项目启动]-开始初始化 elasticsearch 客户端……");
        RestHighLevelClient restHighLevelClient = null;
        // 根据配置文件配置 HttpHost 数组
        final String[] uris = EnvConstant.getStrings("spring.elasticsearch.rest.uris");
        if (uris == null || uris.length == 0) {
            throw new CoreException("[项目启动]-未获取到 elasticsearch 相关配置！");
        }
        final HttpHost[] httpHosts = Arrays.stream(uris).map(HttpHost::create).filter(Objects::nonNull).toArray(HttpHost[]::new);
        // 如果用户名为空则构建无验证的客户端
        final String username = EnvConstant.getString("spring.elasticsearch.rest.username");
        if (StringUtils.isBlank(username)) {
            restHighLevelClient = new RestHighLevelClient(RestClient.builder(httpHosts));
        } else {
            final String password = EnvConstant.getString("spring.elasticsearch.rest.password");
            // 生成凭证
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
            // 生成带验证的客户端构建器
            final RestClientBuilder restClientBuilder = RestClient.builder(httpHosts)
                    .setHttpClientConfigCallback(httpClientBuilder -> {
                        httpClientBuilder.disableAuthCaching();
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    });
            // 返回带验证的客户端
            restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        }
        Logger.info(log, () -> "[项目启动]-初始化 elasticsearch 客户端完成……");
        return restHighLevelClient;
    }


}
